package com.isc.homework01;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * 1.使用字符流的方式，编写一个客户端程序和服务器端程序
 * 2.客户端发送"name"，服务器端接收到后，返回"我是nova",nova是服务器端的名字
 * 3.客户端发送"hobby",服务器端接收到后，返回"编写java程序"
 * 4.如果不是这两个问题,回复"你说啥呢"
 */
public class Server {
    public static void main(String[] args) throws IOException {
        //使用tcp协议通信
        //在8888端口监听
        int port = 8888;
        ServerSocket serverSocket = new ServerSocket(port);
        System.out.println("服务器端在" + port + "端口监听...");

        Socket accept = serverSocket.accept();
        System.out.println("与客户端成功建立连接~");

        //接收客户端发送的数据
        InputStream inputStream = accept.getInputStream();
        BufferedInputStream bis = new BufferedInputStream(inputStream);
        byte[] buf = new byte[1024];
        int dataLength = 0;
        //sb用来存放所有客户端发送的数据
        StringBuilder sb = new StringBuilder();
        while ((dataLength = bis.read(buf)) != -1) {
            sb.append(new String(buf, 0, dataLength));
        }
        System.out.println("接收到客户端的消息是:" + sb);

        //客户端发送"name"，服务器端接收到后，返回"我是nova",nova是服务器端的名字
        OutputStream outputStream = accept.getOutputStream();
        //定义服务器名称
        String serverName = "nova";
        String reply = "";
        if("name".equals(sb.toString())){
//        if("name".equals(msg)){
            //返回"我是nova"
            reply = "我是"+serverName;
        }else if("hobby".equals(sb.toString())){
//        }else if("hobby".equals(msg)){
            //返回"编写java程序"
            reply = "返回\"编写java程序\"";
        }else {
            //如果不是这两个问题,回复"你说啥呢"
            reply = "你说啥呢";
        }
        outputStream.write(reply.getBytes());
        accept.shutdownOutput();//结束符，不能用处理流发送数据，会抛异常
        System.out.println("回复消息成功~");

        //关闭资源
        outputStream.close();
        bis.close();
        accept.close();
        serverSocket.close();
    }
}
